package com.jp.knowledge.my.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.adapter.MessageAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.MessageModel;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/5/10.
 */

public class MessageActivity extends SlidingActivity implements View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener {

    private static final int REFRESH_MESSAGE_LIST = 0x01;
    private static final int LOAD_MORE_MESSAGE_LIST = 0x02;

    @ViewInject(R.id.message_edit_search)
    private EditText searchEdit;
    @ViewInject(R.id.message_iv_clear)
    private ImageView searchClear;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private RecyclerView contentRv;

    private int page;
    private MessageAdapter messageAdapter;
    private List<MessageModel> messageModels;
    private String cachePath;
    private FileCacheManager cacheManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_message;
    }

    @Override
    protected void init() {
        topName.setText("消息");
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.GONE);
        leftIcon.setOnClickListener(this);
        searchClear.setOnClickListener(this);

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        contentRv.setHasFixedSize(true);
        contentRv.setLayoutManager(new LinearLayoutManager(mContext));
        contentRv.addItemDecoration(new JpDiver(mContext));

        cachePath = mContext.getCacheDir() + "/message";
        if(application.getUserData() != null)
            cachePath += ("_" + application.getUserData().getUuid());
        cachePath += ".dat";
        cacheManager = new FileCacheManager();
        page = 1;
        messageModels = new ArrayList<>();
        messageAdapter = new MessageAdapter(mContext, messageModels);
        contentRv.setAdapter(messageAdapter);
        messageAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                startActivity(new Intent(mContext, MessageDetailActivity.class)
                        .putExtra("id", messageModels.get(position).getId())
                        .putExtra("type", messageModels.get(position).getType()));
                messageModels.get(position).setCount(0);
                messageAdapter.notifyItemChanged(position);
            }
        });

        readCache();
    }

    @Override
    public void finish() {
        MyUtil.closeKeyword(this, searchEdit);
        searchEdit.postDelayed(new Runnable() {
            @Override
            public void run() {
                MessageActivity.super.finish();
            }
        }, 300);
    }

    @Override
    protected void onDestroy() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(messageModels, cachePath);
            }
        }).start();
        super.onDestroy();
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<MessageModel>>() {
            @Override
            public void call(Subscriber<? super List<MessageModel>> subscriber) {
                List<MessageModel> data = (List<MessageModel>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<MessageModel>>() {
            @Override
            public void onCompleted() {
                refreshLayout.autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<MessageModel> data) {
                if(data != null) {
                    messageModels = data;
                    messageAdapter.updateAdapter(messageModels);
                }
                onCompleted();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.message_iv_clear:
                searchEdit.setText("");
                break;
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData(page);
    }

    @Override
    public void onLoadMore() {
        getData(++page);
    }

    private void getData(int page){
        JsonObject param = new JsonObject();
        param.addProperty("page", page);
        HttpHelper.getInstance(mContext)
                .messageList(param, (page == 1) ? REFRESH_MESSAGE_LIST : LOAD_MORE_MESSAGE_LIST, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_MESSAGE_LIST)
            refreshLayout.refreshComplete();
        else if(requestType == LOAD_MORE_MESSAGE_LIST)
            refreshLayout.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == REFRESH_MESSAGE_LIST || requestType == LOAD_MORE_MESSAGE_LIST){
            if(requestType == REFRESH_MESSAGE_LIST)
                messageModels.clear();
            List<MessageModel> messageModelList = data.getList(MessageModel.class);
            if(messageModelList != null && messageModelList.size() > 0)
                messageModels.addAll(messageModelList);
            messageAdapter.updateAdapter(messageModels);
        }
    }
}
